package resml

import (
	"io"
	"net/url"
)

// Samba 类型的资源
type SambaResource struct {
	uri    *url.URL
	uriStr string
	append bool

	etager ETager
}

func NewSambaResource(uri *url.URL, etager ETager) *SambaResource {
	return &SambaResource{uri: uri, uriStr: uri.String(), etager: etager}
}

func (r *SambaResource) Append() {
	r.append = true
}

func (r *SambaResource) Uri() string {
	return r.uriStr
}

func (r *SambaResource) Meta() (Meta, error) {
	ss, name, err := sambaSessions.Get(r.uri)
	if err != nil {
		return nil, err
	}
	return ss.Meta(name, r.etager)
}

func (r *SambaResource) Get() (reader io.ReadCloser, meta Meta, err error) {
	ss, name, err := sambaSessions.Get(r.uri)
	if err != nil {
		return nil, nil, err
	}
	return ss.Get(name, r.etager)
}

func (r *SambaResource) Put(meta Meta, reader io.Reader) error {
	return r.do(func(ss *SambaSession, name string) (err error) {
		if r.append {
			_, err = ss.AppendFile(name, -1, reader)
		} else {
			_, err = ss.WriteFile(name, reader)
		}
		return
	})
}

func (r *SambaResource) Remove() error {
	return r.do(func(ss *SambaSession, name string) error {
		return ss.Remove(name)
	})
}

func (r *SambaResource) do(fn func(ss *SambaSession, name string) error) error {
	ss, name, err := sambaSessions.Get(r.uri)
	if err != nil {
		return err
	}
	return fn(ss, name)
}
